package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    //    创建driver对象
    public static WebDriver createDriver(){
//
        if(driver==null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
//            允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            options.addArguments("--proxy-server=http://127.0.0.1:8889");

            driver = new ChromeDriver(options);
//等待页面加载完成
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }
    public Utils(String url){
//        调用driver对象
        driver = createDriver();
        driver.get(url);
//        访问url
    }

    //    这里是截图实现
    public void getScreenShot(String str) throws IOException {

        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());

        String fileTime = sim2.format(System.currentTimeMillis());
//./src/test/image/2021-08-10/test-hour-minute-second-millisecond.png
        String filename = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime+ ".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(filename));

    }

    public void quit() {
        if(driver!=null) {
            driver.quit();
            driver = null;
        }
    }

}
